﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Threading;

public partial class JobManage_PendingJobList : BasePage
{
    DataBase db = new DataBase();
    IJobHandler jobManage = new JobHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISystemHandler systemManage = new SystemHandler();

    IBNTruckHandler truckManage = new BNTruckHandler();
    private static bool isCheck = false;
    ISyContainerModelHandler containerModelManage = new SyContainerModelHandler();

    private static bool isCancel = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1061")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    if (strPermission.Contains("1063"))
                    {
                        isCancel = true;

                    }
                    else
                    {
                        isCancel = false;
                    }
                }
            }

            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "desc";

            ViewState["OrderByT"] = "PKID";
            ViewState["AccendingT"] = "desc";

            btnCancelJobs.Attributes.Add("OnClick", "javascript:return confirm('" + Resources.Messages.ConfirmCancelJob + "');");

            FillDDl();
            dataBind();
            dataBindTruck(GetClientID());
            txtTotalVol.Text = "0";
            txtTotalWeight.Text = "0";
        }
    }

    #region FillDDl
    private void FillDDl()
    {
        //绑定托运人
        DataTable dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        lstShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstShipper.DataTextField = "HKShortName";
        }
        else
        {
            lstShipper.DataTextField = "CNShortName";
        }
        lstShipper.DataValueField = "PKID";
        lstShipper.DataBind();

        //工厂
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.GC.ToString("d")));
        //ddlVendor.DataSource = dt;
        //if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        //{
        //    ddlVendor.DataTextField = "ENGShortName";
        //}
        ddlVendor.Items.Add(new ListItem(Resources.Messages.PleaseSelect, "0"));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem item = new ListItem();
            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                // ddlVendor.DataTextField = "HKShortName";
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["HKShortName"].ToString();
            }
            else
            {
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["CNShortName"].ToString();
                //ddlVendor.DataTextField = "CNShortName";
            }
            item.Value = dt.Rows[i]["PKID"].ToString();
            // ddlVendor.DataValueField = "PKID";
            ddlVendor.Items.Add(item);
        }
        // ddlVendor.DataBind();
        // ddlVendor.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //仓库
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.CK.ToString("d")));
        ddlWhouse.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlWhouse.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlWhouse.DataTextField = "HKShortName";
        }
        else
        {
            ddlWhouse.DataTextField = "CNShortName";
        }
        ddlWhouse.DataValueField = "PKID";
        ddlWhouse.DataBind();
        ddlWhouse.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));
    }
    #endregion
    
   
    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        UsersQuery userQuery = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
        if (userQuery != null)
        {

            list.Add(new SqlParameter("@Contractor", userQuery.ClientID.ToString()));
            sqlstr += " and Contractor=@Contractor ";

            if (ViewState["Shipper"] != null)
            {
               // list.Add(new SqlParameter("@ShipperID", ViewState["ShipperID"].ToString()));
                sqlstr += " and ShipperID in (" + ViewState["Shipper"].ToString() + ")";
            }
            if (ViewState["Whse"] != null)
            {
                list.Add(new SqlParameter("@WhseID", ViewState["Whse"].ToString()));
                sqlstr += " and WhouseID=@WhseID";
            }

            if (ViewState["Vendor"] != null)
            {
                list.Add(new SqlParameter("@VendorID", ViewState["Vendor"].ToString()));
                sqlstr += " and VendorID=@VendorID";

            }

            if (ViewState["DateFrom"] != null && ViewState["DateTo"] != null)
            {
                list.Add(new SqlParameter("@DateFrom", ViewState["DateFrom"].ToString().ToString()));
                list.Add(new SqlParameter("@DateTo", ViewState["DateTo"].ToString()));
                sqlstr += " and JobDate between @DateFrom and @DateTo ";
            }
            else if (ViewState["DateFrom"] != null && ViewState["DateTo"] == null)
            {
                list.Add(new SqlParameter("@DateFrom", ViewState["DateFrom"].ToString().ToString()));
                sqlstr += " and JobDate >= @DateFrom ";
            }
            else if (ViewState["DateFrom"] == null && ViewState["DateTo"] != null)
            {
                list.Add(new SqlParameter("@DateTo", ViewState["DateTo"].ToString().ToString()));
                sqlstr += " and JobDate <= @DateTo ";
            }

            if (ViewState["SONO"] != null)
            {
                list.Add(new SqlParameter("@SONO", txtSONO.Text.Trim()));
                sqlstr += " and SONO like @SONO ";
            }
            list.Add(new SqlParameter("@Status", Enums.ShippingOrderStatus.NEW.ToString("d")));
            list.Add(new SqlParameter("@Status2", Enums.ShippingOrderStatus.CEXPEDITEDTRUCK.ToString("d")));
            sqlstr += " and (Status = @Status or Status=@Status2 )";

            parms = list.ToArray();
        }

    }

    #region dataBind
    private void dataBind()
    {
        if (Session["UserID"] != null)
        {
            string sqlStr = @"SELECT BN.*,WhouseID,SONO,JobDate,GrossWT,VOL,ShipperID,BNDtl.TruckSize,
                            (select Model from Sy_ContainerModel where PKID=BNDtl.TruckSize) as TruckSizeName
                        FROM BN_ShippingOrder as BN,BN_ShippingOrderDtl as BNDtl where BN.PKID=BNDtl.OrderID  ";
            SqlParameter[] parms = null;
            string clause = string.Empty;
            ProcessParms(ref clause, ref parms);
            sqlStr += clause;

            DataTable dt = jobManage.GetShippingOrder(sqlStr, parms);
            DataView view = dt.DefaultView;
            view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
            gvJobList.DataSource = view;
            gvJobList.DataBind();
            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotal.Text = dt.Rows.Count.ToString();
            }
            else
            {
                lblTotal.Text = "0";
            }
        }
        txtTotalVol.Text = "0";
        txtTotalWeight.Text = "0";
    }
    #endregion

    protected void gvJobList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvJobList.PageIndex = e.NewPageIndex;
        dataBind();

    }

    #region gvJobList_RowCommand
    protected void gvJobList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        

        if (e.CommandName == "Cal")//取消Job
        {
            BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(e.CommandArgument.ToString()));

            if (orderQuery != null)
            {
                // if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CANCELCONFIM.ToString("d"))
                //if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CEXPEDITEDTRUCK.ToString("d") || orderQuery.Status.ToString() ==Enums.ShippingOrderStatus.NEW.ToString("d"))//当状态为取消派车状态时才能取消Job
                //{
                    SqlParameter[] parms = new SqlParameter[6];
                    parms[0] = new SqlParameter("@Status", Enums.ShippingOrderStatus.CANCEL.ToString("d"));
                    parms[1] = new SqlParameter("@CancelUser", Session["UserID"].ToString());
                    parms[2] = new SqlParameter("@CancelDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd"));
                    parms[3] = new SqlParameter("@OrderID", e.CommandArgument.ToString());
                    parms[4] = new SqlParameter("@BNDtlStatus", Enums.BookingNoteDtlStatus.CCANCEL.ToString("d"));
                  //  parms[5] = new SqlParameter("@BookingStatus",Enums.BookingStatus.NEW.ToString("d"));
                    parms[5] = new SqlParameter("@Contractor",System.DBNull.Value);
                    string sqlStr = @"update BN_ShippingOrder set Status=@Status,CancelUser=@CancelUser,CancelDate=@CancelDate where PKID=@OrderID;
                                    update BN_BookingDtl set Contractor=@Contractor where BookingID in(select BookingID from BN_ShippingOrder where PKID=@OrderID);
                                    UPDATE BN_BookingNoteDtl SET Status=@BNDtlStatus, CJCancelDate=@CancelDate, CJCancelUser=@CancelUser
                                    WHERE PKID IN (SELECT DISTINCT BookingNoteDtlID FROM BN_BookingDtl WHERE PKID IN 
                                        (SELECT DISTINCT BookingDtlID FROM BN_ShippingOrderDtl WHERE OrderID=@OrderID))";
                //  update BN_Booking set  Status=@BookingStatus where PKID in(select BookingID from BN_ShippingOrder where PKID=@OrderID);
                    //update BN_BookingDtl set Contractor=@Contractor where BookingID in(select BookingID from BN_ShippingOrder where PKID=@OrderID);
                    if (jobManage.ShippingOrderUpdate(sqlStr, parms))
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.CancelSuccess, "PendingJobList.aspx", UpdatePanel1);
                    }
                    else
                    {
                        Jscript.AlertInAjax(Resources.Messages.CancelFailed, UpdatePanel1);
                    }
                //}
                //else
                //{
                //    Jscript.AlertInAjax(Resources.Messages.JobCancel, UpdatePanel1);
                //    return;
                //}
            }
        }
        dataBind();
    }
    #endregion

    protected void gvJobList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    #region btnSearch
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                item += lstSelShipper.Items[i].Value + ",";
            }
            ViewState["Shipper"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Shipper"] = null;
        }

        if (ddlVendor.SelectedValue != "0")
        {

            ViewState["Vendor"] = ddlVendor.SelectedValue;
        }
        else
        {
            ViewState["Vendor"] = null;
        }
        if (ddlWhouse.SelectedValue != "0")
        {

            ViewState["Whse"] = ddlWhouse.SelectedValue;
        }
        else
        {
            ViewState["Whse"] = null;
        }

        if (txtDateFrom.Text != string.Empty && txtDateTo.Text != string.Empty)
        {
            ViewState["DateFrom"] = txtDateFrom.Text.Trim() + " 00:00:00";

            ViewState["DateTo"] = txtDateTo.Text.Trim() + " 23:59:59";
        }
        else if (txtDateFrom.Text != string.Empty && txtDateTo.Text == string.Empty)
        {
            ViewState["DateFrom"] = txtDateFrom.Text.Trim() + " 23:59:59";

            ViewState["DateTo"] = null;
        }
        else if (txtDateFrom.Text == string.Empty && txtDateTo.Text != string.Empty)
        {

            ViewState["DateFrom"] = null;
            ViewState["DateTo"] = txtDateTo.Text.Trim() + " 23:59:59";
        }
        else
        {
            ViewState["DateFrom"] = null;
            ViewState["DateTo"] = null;
        }

        if (txtSONO.Text != string.Empty)
        {
            ViewState["SONO"] = txtSONO.Text.Trim();
        }
        else
        {
            ViewState["SONO"] = null;
        }
     

        dataBind();
    }
    #endregion

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvJobList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvJobList.PageCount)
            {
                this.gvJobList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);
                return;
            }
        }
        catch
        {
            Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvJobList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }
       

    private void dataBindTruck(int clientID)
    {
        DataTable dt = truckManage.GetTruckList(clientID);
        gvTruckList.DataSource = dt;
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderByT"] + " " + ViewState["AccendingT"];
        gvTruckList.DataSource = view;
        gvTruckList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotalTruck.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotalTruck.Text = "0";
        }
    }


    protected void ddlPagesTruck_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvTruckList.PageSize = int.Parse(ddlPagesTruck.SelectedValue);
        dataBindTruck(GetClientID());
    }

    protected void gvTruckList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvTruckList.PageIndex = e.NewPageIndex;
        dataBindTruck(GetClientID());
    }
  

    protected void gvTruckList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderByT"].ToString().ToLower())
        {
            if (ViewState["AccendingT"].ToString().ToLower() == "asc")
            {
                ViewState["AccendingT"] = "desc";
            }
            else
            {
                ViewState["AccendingT"] = "asc";
            }
        }
        else
        {
            ViewState["OrderByT"] = e.SortExpression;
        }

        dataBindTruck(GetClientID());
    }   
       
    protected void lbtnGoTruck_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvTruckList.BottomPagerRow.FindControl("txtPagesTruck"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvTruckList.PageCount)
            {
                this.gvTruckList.PageIndex = i;
                //数据绑定
                dataBindTruck(GetClientID());
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);

        }
    }

    public string GetDriver(object id)
    {
        return systemManage.GetDriver(id);
    }

    private int GetClientID()
    {
        int clientID = 0;
        if (Session["UserID"] != null)
        {
            UsersQuery query = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
            if (query != null)
            {
                clientID = query.ClientID;
            }
        }
        return clientID;
    }

    public string GetClient(object id)
    {
        return systemManage.GetClient(id);
    }

    public string GetUserName(object userID)
    {
        return systemManage.GetUserName(userID);
    }

    public string GetType(object typeID)
    {
        string model = string.Empty;
        Sy_ContainerModelQuery query = containerModelManage.GetModel(int.Parse(typeID.ToString()));
        if (query != null)
        {
            return model = query.Model;
        }
        return model;
    }

    private DataTable GetModel()
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@Status", "1");
        string sqlSTr = "select * from Sy_ContainerModel where Status=@Status";

        return containerModelManage.GetModelList(sqlSTr, parms);

    }


    #region //全选代码

    ///   <summary>   
    ///   获取或设置选中项的集合   
    ///   </summary>   
    protected ArrayList SelectedItems
    {
        get
        {
            return (ViewState["mySelectedItems"] != null) ? (ArrayList)ViewState["mySelectedItems"] : null;
        }
        set
        {
            ViewState["mySelectedItems"] = value;
        }
    }

    protected ArrayList SelectedItems2
    {
        get
        {
            return (ViewState["mySelectedItems2"] != null) ? (ArrayList)ViewState["mySelectedItems2"] : null;
        }
        set
        {
            ViewState["mySelectedItems2"] = value;
        }
    }

    ///   <summary>   
    ///   从当前页收集选中项的情况   
    ///   </summary>   
    protected void CollectSelected()
    {
        ArrayList selectedItems = null;
        if (this.SelectedItems == null)
            selectedItems = new ArrayList();
        else
            selectedItems = this.SelectedItems;

        for (int i = 0; i < this.gvJobList.Rows.Count; i++)
        {
            HiddenField hidID = (HiddenField)gvJobList.Rows[i].Cells[1].FindControl("hidID");
            string id = hidID.Value;
            CheckBox cb = this.gvJobList.Rows[i].FindControl("CheckBox1") as CheckBox;
            if (selectedItems.Contains(id) && !cb.Checked)
                selectedItems.Remove(id);
            if (!selectedItems.Contains(id) && cb.Checked)
                selectedItems.Add(id);
        }
        this.SelectedItems = selectedItems;
    }

    protected void CollectSelected2()
    {
        ArrayList selectedItems = null;
        if (this.SelectedItems2 == null)
            selectedItems = new ArrayList();
        else
            selectedItems = this.SelectedItems2;

        for (int i = 0; i < this.gvTruckList.Rows.Count; i++)
        {
            HiddenField hidID = (HiddenField)gvTruckList.Rows[i].Cells[1].FindControl("hidID");
            string id = hidID.Value;
            CheckBox cb = this.gvTruckList.Rows[i].FindControl("CheckBox2") as CheckBox;
            if (selectedItems.Contains(id) && !cb.Checked)
                selectedItems.Remove(id);
            if (!selectedItems.Contains(id) && cb.Checked)
                selectedItems.Add(id);
        }
        this.SelectedItems2 = selectedItems;
    }

    protected void gvJobList_DataBinding(object sender, EventArgs e)
    {
        //在每一次重新绑定之前，需要调用CollectSelected方法从当前页收集选中项的情况   
        CollectSelected();
    }


    protected void gvJobList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //这里的处理是为了回显之前选中的情况   
        if (e.Row.RowIndex > -1 && this.SelectedItems != null)
        {
            DataRowView row = e.Row.DataItem as DataRowView;
            CheckBox cb = e.Row.FindControl("CheckBox1") as CheckBox;
            if (this.SelectedItems.Contains(row["PKID"].ToString()))
                cb.Checked = true;
            else
                cb.Checked = false;
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton btnCancel = (LinkButton)e.Row.FindControl("lbtnCal");
            HiddenField hidOrderID = (HiddenField)e.Row.FindControl("hidOrderID");
          
            if (hidOrderID.Value != string.Empty)
            {
                BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(hidOrderID.Value));
                if (orderQuery != null)
                {
                    if (isCancel)
                    {

                        if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CEXPEDITEDTRUCK.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.NEW.ToString("d"))
                        {
                            btnCancel.Visible = true;
                        }
                        else
                        {
                            btnCancel.Visible = false;
                        }
                    }
                    else
                    {
                        btnCancel.Visible = false;
                    }
                }
            }
        }

    }

    protected void gvTruckList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //这里的处理是为了回显之前选中的情况   
        if (e.Row.RowIndex > -1 && this.SelectedItems != null)
        {
            DataRowView row = e.Row.DataItem as DataRowView;
            CheckBox cb = e.Row.FindControl("CheckBox2") as CheckBox;
            if (this.SelectedItems.Contains(row["PKID"].ToString()))
                cb.Checked = true;
            else
                cb.Checked = false;
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlType = (DropDownList)e.Row.FindControl("ddlType");
            HiddenField hidType = (HiddenField)e.Row.FindControl("hidType");
            ddlType.DataSource = GetModel();
            ddlType.DataTextField = "Model";
            ddlType.DataValueField = "PKID";
            ddlType.DataBind();
           // ddlType.Items.Insert(0, new ListItem("请选择...", "0"));

            ddlType.SelectedValue = hidType.Value;

            HiddenField hidTruckID = (HiddenField)e.Row.FindControl("hidTruckID");
            DropDownList ddlTruckNos = (DropDownList)e.Row.FindControl("ddlLicenseNO");
            DropDownList ddlLicenseNOSearch = (DropDownList)e.Row.FindControl("ddlLicenseNOSearch");
            ddlTruckNos.DataSource = truckManage.GetTruckList(GetClientID());
            ddlTruckNos.DataTextField = "LicenseNO";
            ddlTruckNos.DataValueField = "PKID";
            ddlTruckNos.DataBind();

            ddlTruckNos.SelectedValue = hidTruckID.Value;


            ddlLicenseNOSearch.DataSource = truckManage.GetTruckList(GetClientID());
            ddlLicenseNOSearch.DataTextField = "LicenseNO";
            ddlLicenseNOSearch.DataValueField = "PKID";
            ddlLicenseNOSearch.DataBind();

            ddlLicenseNOSearch.SelectedValue = hidTruckID.Value;
           
        }
    }

    protected void gvTruckList_DataBinding(object sender, EventArgs e)
    {  //在每一次重新绑定之前，需要调用CollectSelected方法从当前页收集选中项的情况   
        CollectSelected2();

    }

    #endregion




    //泒车
    protected void btnCheck_Click(object sender, EventArgs e)
    {

        CollectSelected();
        CollectSelected2();
        string sqlStr = string.Empty;
        if (this.SelectedItems != null && this.SelectedItems.Count > 0 && this.SelectedItems2 != null && this.SelectedItems2.Count > 0)
        {


            SqlParameter[] parms = null;
            List<SqlParameter> list = new List<SqlParameter>();
            int jj = 0;

            if (txtAppointmentNO.Text != string.Empty)
            {
                list.Add(new SqlParameter("@Appointment", txtAppointmentNO.Text));
            }

            list.Add(new SqlParameter("@Status", Enums.ShippingOrderStatus.CHECK.ToString("d")));// ShippingOrder 运输队审核状态
            list.Add(new SqlParameter("@CheckDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd")));
            list.Add(new SqlParameter("@CheckUser", Session["UserID"].ToString()));
            list.Add(new SqlParameter("@Contractor", GetClientID().ToString()));
            list.Add(new SqlParameter("@LastModUser", Session["UserID"].ToString()));
            list.Add(new SqlParameter("@LastModDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd")));
            list.Add(new SqlParameter("@Remark", string.Empty));
            list.Add(new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.CCONFIRM.ToString("d")));//BookingNoteDtl 运输队确认Job状态
            string sendCode = FileTools.AutoFileName();
            list.Add(new SqlParameter("@SendCode", sendCode));

            decimal vol = 0;
            decimal littleVol = 0;
            decimal greateVol = 0;

            for (int i = 0; i < SelectedItems.Count; i++)
            {
                list.Add(new SqlParameter("@OrderID" + i.ToString(), SelectedItems[i].ToString()));

                SqlParameter parm = new SqlParameter("@ReturnValue" + i.ToString(), 0);
                parm.SqlDbType = SqlDbType.Int;
                parm.Direction = ParameterDirection.Output;

                list.Add(parm);


                //计算选择了的Total Vol
                SqlParameter[] parmsV = new SqlParameter[1];
                parmsV[0] = new SqlParameter("@OrderIDV", SelectedItems[i].ToString());
                DataTable dt = jobManage.GetShippingOrderDtl("select * from BN_ShippingOrderDtl where OrderID=@OrderIDV",parmsV);
                if (dt != null && dt.Rows.Count > 0)
                {
                    vol += decimal.Parse(dt.Rows[0]["VOL"].ToString());
                }


                if (txtAppointmentNO.Text != string.Empty)
                {
                    sqlStr += "update BN_ShippingOrder set Status=@Status,CheckDate=@CheckDate,CheckUser=@CheckUser,Appointament=@Appointment where PKID=@OrderID" + i.ToString() + ";";
                    sqlStr += "update BN_BookingNoteDtl set Appointament=@Appointment where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID" + i.ToString() + "));";
                    sqlStr += "update BN_BookingDtl set Appointament=@Appointment where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID" + i.ToString() + ");";
                }
                else
                {
                    sqlStr += "update BN_ShippingOrder set Status=@Status,CheckDate=@CheckDate,CheckUser=@CheckUser where PKID=@OrderID" + i.ToString() + ";";

                }
                sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,CJDate=@CheckDate,CJUser=@CheckUser where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID" + i.ToString() + ")); ";
                sqlStr += "insert into BN_SendTruck(SendNO,OrderID,Contractor,LastModUser,LastModDate,Remark,SendCode) values(dbo.Fn_NextSendNO(),@OrderID" + i.ToString() + ",@Contractor,@LastModUser,@LastModDate,@Remark,@SendCode) SET @ReturnValue" + i.ToString() + "=@@Identity;";


                // string[] trucks = Request["chkSelected"].Split(new char[] { ',' });
                for (int j = 0; j < SelectedItems2.Count; j++)
                {
                    jj += 1;
                    //list.Add(new SqlParameter("@TruckID" + jj.ToString(), SelectedItems2[j].ToString()));
                  

                    //BN_TruckQuery query = truckManage.GetTruckByID(int.Parse(SelectedItems2[j].ToString()));
                    //if (query != null)
                    //{
                    //    list.Add(new SqlParameter("@Drive" + jj.ToString(), query.Driver));
                    //}
                    //else
                    //{
                    //    list.Add(new SqlParameter("@Drive" + jj.ToString(), string.Empty));
                    //}

                    //获取车型,车牌号，司机
                    for (int m = 0; m < gvTruckList.Rows.Count; m++)
                    {
                        HiddenField hidPKID = (HiddenField)gvTruckList.Rows[m].FindControl("hidPKID");
                        DropDownList ddlType = (DropDownList)gvTruckList.Rows[m].FindControl("ddlType");

                        DropDownList ddlTruckNo = (DropDownList)gvTruckList.Rows[m].FindControl("ddlLicenseNO");

                        if (SelectedItems2[j].ToString() == hidPKID.Value)
                        {
                            list.Add(new SqlParameter("@TypeID" + jj.ToString(), ddlType.SelectedValue));
                            list.Add(new SqlParameter("@TruckID"+jj.ToString(),ddlTruckNo.SelectedValue));

                            BN_TruckQuery query = truckManage.GetTruckByID(int.Parse(ddlTruckNo.SelectedValue));
                            if (query != null)
                            {
                                list.Add(new SqlParameter("@Drive" + jj.ToString(), query.Driver));
                            }
                            else
                            {
                                list.Add(new SqlParameter("@Drive" + jj.ToString(), string.Empty));
                            }
                        }
                    }

                    sqlStr += "insert into BN_SendTruckDtl(SendTruckID,TruckID,Driver,Remark,TypeID) values(@ReturnValue" + i.ToString() + ",@TruckID" + jj.ToString() + ",@Drive" + jj.ToString() + ",@Remark" + ",@TypeID" + jj.ToString() + ");";
                }
            }

            //计算选择了的车型的VOL
            for (int i = 0; i < SelectedItems2.Count; i++)
            {
                //获取车型
                for (int m = 0; m < gvTruckList.Rows.Count; m++)
                {
                    HiddenField hidPKID = (HiddenField)gvTruckList.Rows[m].FindControl("hidPKID");
                    DropDownList ddlType = (DropDownList)gvTruckList.Rows[m].FindControl("ddlType");
                    if (SelectedItems2[i].ToString() == hidPKID.Value)
                    {
                        Sy_ContainerModelQuery query = containerModelManage.GetModel(int.Parse(ddlType.SelectedValue));
                        if (query != null)
                        {
                            littleVol += query.VolLowerLimit;
                            greateVol += query.VolUpperLimit;
                        }
                    }
                }
            }

            parms = list.ToArray();

           
            if (jobManage.ShippingOrderUpdate(sqlStr, parms))
            {
                //Jscript.AlertAndRedirectInAjax(Resources.Messages.CheckSuccess, "PendingJobList.aspx", UpdatePanel1);
                if (vol < littleVol)
                {
                    Jscript.AlertAndRedirectInAjax("分派成功,選擇的總CBM比車型的總CBM要小!", "PendingJobList.aspx", UpdatePanel1);
                }
                else if (vol > greateVol)
                {
                    Jscript.AlertAndRedirectInAjax("分派成功,選擇的總CBM比車型的總CBM要大!", "PendingJobList.aspx", UpdatePanel1);
                }
                else
                {
                    Jscript.AlertAndRedirectInAjax("分派成功!", "PendingJobList.aspx", UpdatePanel1); 
                }
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.CheckFailed, UpdatePanel1);
            }
        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.SendTruck, UpdatePanel1);
            return;

        }
    }


    protected void btnCancelJobs_Click(object sender, EventArgs e)
    {
        CollectSelected();
        if (this.SelectedItems != null && this.SelectedItems.Count > 0)
        {
            SqlParameter[] parms = null;
            List<SqlParameter> list = new List<SqlParameter>();
            string sqlStr=string.Empty;

            list.Add(new SqlParameter("@Status", Enums.ShippingOrderStatus.CANCEL.ToString("d")));
            list.Add(new SqlParameter("@CancelUser", Session["UserID"].ToString()));
            list.Add( new SqlParameter("@CancelDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd")));
            list.Add( new SqlParameter("@BNDtlStatus", Enums.BookingNoteDtlStatus.CCANCEL.ToString("d")));
            //list.Add( new SqlParameter("@BookingStatus", Enums.BookingStatus.NEW.ToString("d")));
            //list.Add( new SqlParameter("@Contractor", System.DBNull.Value));

            for (int i = 0; i < SelectedItems.Count; i++)
            {
                BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(SelectedItems[i].ToString()));
                
                if (orderQuery != null)
                {
                    // if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CANCELCONFIM.ToString("d"))
                    if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CEXPEDITEDTRUCK.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.NEW.ToString("d"))//当状态为取消派车状态时才能取消Job
                    {                      
                       
                      list.Add( new SqlParameter("@OrderID"+i.ToString(), SelectedItems[i].ToString()));
                       
                         sqlStr += "update BN_ShippingOrder set Status=@Status,CancelUser=@CancelUser,CancelDate=@CancelDate where PKID=@OrderID"+i.ToString() +";";
                           // sqlStr +="update BN_Booking set  Status=@BookingStatus where PKID in(select BookingID from BN_ShippingOrder where PKID=@OrderID" + i.ToString() +");";
                           // sqlStr += "update BN_BookingDtl set Contractor=@Contractor where BookingID in(select BookingID from BN_ShippingOrder where PKID=@OrderID" + i.ToString() +");";
                             sqlStr +=" UPDATE BN_BookingNoteDtl SET Status=@BNDtlStatus, CJCancelDate=@CancelDate, CJCancelUser=@CancelUser WHERE PKID IN (SELECT DISTINCT BookingNoteDtlID FROM BN_BookingDtl WHERE PKID IN (SELECT DISTINCT BookingDtlID FROM BN_ShippingOrderDtl WHERE OrderID=@OrderID" +i.ToString() +"));";
                                             
                    }                   
                }
            }
            parms = list.ToArray();

            if (jobManage.ShippingOrderUpdate(sqlStr, parms))
            {
                Jscript.AlertAndRedirectInAjax(Resources.Messages.CancelSuccess, "PendingJobList.aspx", UpdatePanel1);
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.CancelFailed, UpdatePanel1);
            }

            dataBind();
        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel1);
        }

    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (lstShipper.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstShipper.Items.Count; i++)
            {
                bool issel = false;
                if (lstShipper.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelShipper.Items.Count; j++)
                    {
                        if (lstShipper.Items[i].Value == lstSelShipper.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstShipper.Items[i].Text;
                        item.Value = lstShipper.Items[i].Value;
                        lstSelShipper.Items.Add(item);
                    }
                }
            }
        }
        else
        {

        }

    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                if (!lstSelShipper.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelShipper.Items[i].Text, lstSelShipper.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelShipper.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelShipper.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelShipper.Items.Clear();
            }

        }
    }
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        decimal vol = 0;
        double weight = 0d;

        for (int i = 0; i < this.gvJobList.Rows.Count; i++)
        {
            HiddenField hidID = (HiddenField)gvJobList.Rows[i].Cells[1].FindControl("hidID");
            string id = hidID.Value;
            CheckBox cb = this.gvJobList.Rows[i].FindControl("CheckBox1") as CheckBox;
            if (cb.Checked)
            {
                string sqlStr = "select * from BN_ShippingOrderDtl where OrderID=@OrderID";
                SqlParameter[] parms = new SqlParameter[1];
                parms[0] = new SqlParameter("@OrderID", id);
                DataTable dt = jobManage.GetShippingOrderDtl(sqlStr, parms);
                if (dt != null && dt.Rows.Count > 0)
                {
                    vol += decimal.Parse(dt.Rows[0]["Vol"].ToString());
                    weight += double.Parse(dt.Rows[0]["GrossWT"].ToString());
                }
            }

        }
        txtTotalVol.Text = vol.ToString();
        txtTotalWeight.Text = weight.ToString();
    }

    protected void chkAll_CheckedChanged(object sender, EventArgs e)
    {
        decimal vol = 0;
        double weight = 0d;

        for (int i = 0; i < this.gvJobList.Rows.Count; i++)
        {
            HiddenField hidID = (HiddenField)gvJobList.Rows[i].Cells[1].FindControl("hidID");
            string id = hidID.Value;
            CheckBox cb = this.gvJobList.Rows[i].FindControl("CheckBox1") as CheckBox;
            if (cb.Checked)
            {
                string sqlStr = "select * from BN_ShippingOrderDtl where OrderID=@OrderID";
                SqlParameter[] parms = new SqlParameter[1];
                parms[0] = new SqlParameter("@OrderID", id);
                DataTable dt = jobManage.GetShippingOrderDtl(sqlStr, parms);
                if (dt != null && dt.Rows.Count > 0)
                {
                    vol += decimal.Parse(dt.Rows[0]["Vol"].ToString());
                    weight += double.Parse(dt.Rows[0]["GrossWT"].ToString());
                }
            }

        }
        txtTotalVol.Text = vol.ToString();
        txtTotalWeight.Text = weight.ToString();
    }
}
